<?php
include __DIR__ . "/config/cors.php";
include __DIR__ . "/database.php";


$username = @$_POST['username'];
$role = @$_POST['role'];
$newImg = @$_POST['newImg'];
$title = @$_POST['title'];
$context = @$_POST['context'];

if (!isset($username) or !isset($role)) {
    echo json_encode([
        "code" => 203,
        "message" => "请登陆后再发布新闻"
    ]);
    exit;
} else if (!isset($title) or $title == "" or !isset($context) or $context == "") {
    echo json_encode([
        "code" => 201,
        "message" => "缺少标题或正文"
    ]);
    exit;
}

$db = new DB();
$sql = "select * from user where username = '$username'";
$data = $db->selectOne($sql);
if (is_array($data) and count($data) > 0) {
    $uid = $data['id'];
    $sql = "insert into news(uid, title, context, time, newImg)
            values('$uid', '$title', '$context', NOW(), '$newImg')";
    if ($db->execute($sql)) {
        echo json_encode([
            "code" => 200,
            "message" => "发布新闻成功"
        ]);
    } else {
        echo json_encode([
            "code" => 205,
            "message" => "发布新闻失败"
        ]);
    }
} else {
    echo json_encode([
        "code" => 203,
        "message" => "请登陆后再发布新闻"
    ]);
}
